package com.itheima.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.Service.ShoppingCartService;
import com.itheima.reggie.exception.BaseContext;
import com.itheima.reggie.exception.R;
import com.itheima.reggie.pojo.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
  @GetMapping("/list")
    public R<List<ShoppingCart>>  list(HttpSession session)
    {
        Long id=(Long) session.getAttribute("user");
           QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
           queryWrapper.eq("user_id",id);
         List<ShoppingCart> list=  shoppingCartService.list(queryWrapper);
         return R.success(list);
    }
    @PostMapping("/add")
    public R<String> add(@RequestBody ShoppingCart shoppingCart, HttpSession session)
    {
        //设置用户id,给那个用户加购物车
        Long curdID=(Long)session.getAttribute("user");
        shoppingCart.setUserId(curdID);
        //查询当前菜和套餐是否在购物车中
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",curdID);
        Long dishId=shoppingCart.getDishId();
        if(dishId!=null)
        {
            //菜品添加
            queryWrapper.eq("dish_id",dishId);
        }
        //套餐添加
   queryWrapper.eq("setmeal_id",shoppingCart.getSetmealId());
   ShoppingCart shoppingCart1= shoppingCartService.getOne(queryWrapper);
   if(shoppingCart1!=null)
   {
      Integer num= shoppingCart1.getNumber();
      shoppingCart1.setNumber(num+1);
      shoppingCartService.updateById(shoppingCart1);

   }
   else {
       shoppingCart.setNumber(1);
       shoppingCartService.save(shoppingCart);
   }
   return R.success("添加成功");
    }

    @DeleteMapping("/clean")
    public R<String> delete(HttpSession session)
    {
        Long id=(Long) session.getAttribute("user");
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",id);
        shoppingCartService.remove(queryWrapper);
        return R.success("删除成功");
    }
}
